gusucode.com > VC Access数据库创建读写实例 > VC Access数据库创建读写实例/RWAccess/RWAccessDlg.cpp

    //////////////////////////////////////////////////////////////////////////////
//类名:CRWAccessDlg
//功能:直接通过DAO读、写Access文件示例实现
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "RWAccess.h"
#include "RWAccessDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

CDaoDatabase db;				//数据库
CDaoRecordset RecSet(&db);		//记录集
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

	//绘制荣誉显示框中的闪电效果
	static void DrawCreditsBackground(CDC *pDC, RECT rect, BOOL bAnimate, DWORD lParam);

	void SizeWindow(int ReduceHeight, bool bExtend);    //伸展或收缩对话框    
	
	//"关于"对话框中的荣誉显示
	int m_nReducedHeight;								//收缩状态下的窗口高度 
	
	bool m_bVertical;									//是否显示荣誉标志

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	CXPButton	m_More;									//XP风格按钮
	CHyperLink	m_Mail;									//超链接形式显示EMAIL
	CXPButton	m_OK;									//XP风格按钮
	CPictureEx	m_Flag;									//GIF动态图像显示
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	CCreditsCtrl m_wndCredits;							//荣誉显示

	//{{AFX_MSG(CAboutDlg)
	virtual BOOL OnInitDialog();
	afx_msg void OnMore();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	DDX_Control(pDX, ID_MORE, m_More);
	DDX_Control(pDX, IDC_STATIC_MAIL, m_Mail);
	DDX_Control(pDX, IDOK, m_OK);
	DDX_Control(pDX, IDC_FLAG, m_Flag);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
	ON_BN_CLICKED(ID_MORE, OnMore)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

//////////////////////////////////////////////////////////////////////////////
//名称:OnInitDialog
//功能:初始化"关于"对话框
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
BOOL CAboutDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();

	//对话框居中显示
	CRect dlgRect; 
	GetWindowRect(dlgRect);  
	CRect desktopRect; 
	GetDesktopWindow()->GetWindowRect(desktopRect); 

	MoveWindow( 
		(desktopRect.Width() - dlgRect.Width()) / 2, 
		(desktopRect.Height() - dlgRect.Height()) / 2, 
		0, 
		0 ); 

	//"关于"对话框中对话框可收缩效果
	CRect Rect1,Rect2; 												//对话框收缩时大小		
	
	GetDlgItem(IDC_DYCREDITS)->GetWindowRect(Rect1); 
	GetDlgItem(IDC_COPYRIGHT)->GetWindowRect(Rect2); 
	m_nReducedHeight = Rect1.Height()+(Rect1.top -Rect2.bottom)/2; //收缩后窗体高度
	dlgRect.bottom -= (Rect1.Height()+(Rect1.top -Rect2.bottom)/2); 
	MoveWindow(&dlgRect);											//如果要显示对话框起始动态效果的话,不能使用该句

	m_bVertical=false;			

	//加入EMAIL的超连接
    m_Mail.SetURL(_T("mailto:jingzhou_xu@163.net"));
	m_Mail.SetUnderline(FALSE);	

	//显示动态GIF图像logo
	if(m_Flag.Load(MAKEINTRESOURCE(IDR_FLAG),_T("GIF")))
	{
		m_Flag.SetBkColor(RGB(160,180,220));
		m_Flag.Draw();	
	}

	//显示荣誉效果框
	srand((unsigned)time(NULL));

	// 内容
	CString s;
	s = "<font color='255,255,255' face='宋体' size='12' align='center'><br><p>";
	s += "<font color='200,250,100' size='18' face='宋体' style='ui'>直接通过DAO读、写Access文件示例</font><br><br><p>";
	s += "<font color='200,250,100' size='14' face='宋体'>作者:徐景周</font><br><br><p>";
	s += "<font color='200,250,100' size='14' face='宋体'>未来工作室出品</font><br><p>";

	//格式化并加入字符串
	m_wndCredits.FormatDataString(s);
	
	// 绘制闪电效果
	m_wndCredits.m_pBackgroundPaint = CAboutDlg::DrawCreditsBackground;
	m_wndCredits.m_dwBackgroundPaintLParam = TRUE;

	// 默认背景置黑色
	m_wndCredits.m_crInternalTransparentColor = RGB(255,255,255);

	//滚动速度
	m_wndCredits.m_nTimerSpeed = 40;

	//用户拖拉滚动
	m_wndCredits.m_bCanScroll = TRUE;
	
	// 创建荣誉框
	m_wndCredits.Create(WS_EX_CLIENTEDGE,WS_VISIBLE|WS_CHILD,IDC_DYCREDITS,this,0,0,0);

	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

// ---------------------------------------------------------
//	名称: OnMore
//	功能: 是否荣誉显示
//	变量: 无
//	返回: 无
//	编写: 徐景周,2002.4.8
// ---------------------------------------------------------
void CAboutDlg::OnMore() 
{
	m_bVertical = !m_bVertical; 
	
	if(m_bVertical == FALSE)	//不显示
	{ 
		SetDlgItemText(ID_MORE,_T("更多>>"));

		SizeWindow(m_nReducedHeight,true);
	} 
	else						//显示
	{ 
		SetDlgItemText(ID_MORE,_T("<<隐藏"));

		SizeWindow(m_nReducedHeight,false);
	} 
	
	UpdateWindow(); 
}

// ---------------------------------------------------------
//	名称: SizeWindow
//	功能: 伸展或收缩对话框    
//	变量: ReduceHeight-收缩高度,bExtend-是否伸展
//	返回: 无
//	编写: 徐景周,2002.4.8
// ---------------------------------------------------------	
void CAboutDlg::SizeWindow(int ReduceHeight, bool bExtend)
{
	CRect rc;
	GetWindowRect(&rc);
	if(bExtend)
	{
		for (int i= 0; i < ReduceHeight; i++)
		{
			rc.bottom--;
			MoveWindow(&rc);
		}
	}
	else
	{
		for (int i= 0; i < ReduceHeight; i++)
		{
			rc.bottom++;
			MoveWindow(&rc);
		}
	}
}

// ---------------------------------------------------------
//	名称: DrawCreditsBackground
//	功能: 绘制荣誉框中闪电效果   
//	变量: pDC -- 环境指针,rect -- 范围,bAnimate -- 动画效果,lParam -- 消息参数
//	返回: 无
//	编写: 徐景周,2002.4.8
// ---------------------------------------------------------	
void CAboutDlg::DrawCreditsBackground(CDC *pDC, RECT rect, BOOL bAnimate, DWORD lParam)
{
	static int on1,on2,oon1,oon2;
	pDC->FillSolidRect(&rect,0x00000000);
	
	if(bAnimate || (!lParam)) // return now if we are not supposed to do the animation
		return;

	int n1,n2;
	n1 = rand()*200/RAND_MAX-100;
	n2 = rand()*200/RAND_MAX-100;

	// 2/10 chance of (prehaps) making some wild stuff on one of the curves
	if(rand() < RAND_MAX/10)
		n1 = rand()*400/RAND_MAX-200;
	else if(rand() < RAND_MAX/10)
		n2 = rand()*400/RAND_MAX-200;

	POINT points1[4] = {
		rect.right,0,
		(rect.right-rect.left)/2+n1,(rect.bottom-rect.top)/2,
		(rect.right-rect.left)/2,(rect.bottom-rect.top)/2-n1,
		0,rect.bottom
	};
	POINT points2[4] = {
		0,0,
		(rect.right-rect.left)/2-n2,(rect.bottom-rect.top)/2,
		(rect.right-rect.left)/2,(rect.bottom-rect.top)/2-n2,
		rect.right,rect.bottom
	};
	POINT opoints1[4] = {
		rect.right,0,
		(rect.right-rect.left)/2+on1,(rect.bottom-rect.top)/2,
		(rect.right-rect.left)/2,(rect.bottom-rect.top)/2-on1,
		0,rect.bottom
	};
	POINT opoints2[4] = {
		0,0,
		(rect.right-rect.left)/2-on2,(rect.bottom-rect.top)/2,
		(rect.right-rect.left)/2,(rect.bottom-rect.top)/2-on2,
		rect.right,rect.bottom
	};
	POINT oopoints1[4] = {
		rect.right,0,
		(rect.right-rect.left)/2+oon1,(rect.bottom-rect.top)/2,
		(rect.right-rect.left)/2,(rect.bottom-rect.top)/2-oon1,
		0,rect.bottom
	};
	POINT oopoints2[4] = {
		0,0,
		(rect.right-rect.left)/2-oon2,(rect.bottom-rect.top)/2,
		(rect.right-rect.left)/2,(rect.bottom-rect.top)/2-oon2,
		rect.right,rect.bottom
	};

	CPen wpen(PS_SOLID,1,RGB(150,220,255));
	CPen pen(PS_SOLID,2,RGB(50,100,255));
	CPen open(PS_SOLID,1,RGB(50,100,255));
	CPen oopen(PS_SOLID,1,RGB(0,30,150));
	CPen *pOldPen = pDC->SelectObject(&oopen);
	pDC->PolyBezier(oopoints1,4);
	pDC->PolyBezier(oopoints2,4);
	pDC->SelectObject(&open);
	pDC->PolyBezier(opoints1,4);
	pDC->PolyBezier(opoints2,4);
	pDC->SelectObject(&pen);
	pDC->PolyBezier(points1,4);
	pDC->PolyBezier(points2,4);
	pDC->SelectObject(&wpen);
	pDC->PolyBezier(points1,4);
	pDC->PolyBezier(points2,4);
	pDC->SelectObject(pOldPen);

	oon1 = on1;
	oon2 = on2;
	on1 = n1;
	on2 = n2;
}

/////////////////////////////////////////////////////////////////////////////
// CRWAccessDlg dialog

CRWAccessDlg::CRWAccessDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRWAccessDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CRWAccessDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CRWAccessDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRWAccessDlg)
	DDX_Control(pDX, IDC_LISTACCESS, m_AccessList);
	DDX_Control(pDX, IDOK, m_OK);
	DDX_Control(pDX, IDC_WRITEACCESS, m_WriteAccess);
	DDX_Control(pDX, IDC_READACCESS, m_ReadAccess);
	DDX_Control(pDX, IDC_ABOUT, m_About);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRWAccessDlg, CDialog)
	//{{AFX_MSG_MAP(CRWAccessDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_WRITEACCESS, OnWriteAccess)
	ON_BN_CLICKED(IDC_READACCESS, OnReadAccess)
	ON_BN_CLICKED(IDC_ABOUT, OnAbout)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRWAccessDlg message handlers
//////////////////////////////////////////////////////////////////////////////
//名称:OnInitDialog
//功能:初始化对话框
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
BOOL CRWAccessDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRWAccessDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRWAccessDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRWAccessDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

//////////////////////////////////////////////////////////////////////////////
//名称:OnWriteAccess
//功能:创建并写入数据到Access文件中
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
void CRWAccessDlg::OnWriteAccess() 
{
	//获取主程序所在路径,存在sPath中
	CString sPath;
	GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
	sPath.ReleaseBuffer ();
	int nPos;
	nPos=sPath.ReverseFind ('\\');
	sPath=sPath.Left (nPos);

	//默认创建数据名:Demo.mdb,内部表名:DemoTable,表内有二个字段:姓名、年龄
	CString lpszFile = sPath + "\\Demo.mdb";
	
	CFileFind  fFind;
	BOOL bSuccess;
	bSuccess=fFind.FindFile(lpszFile);

	fFind.Close ();
    //是否已有创建好的Demo.mdb文件,没有则创建它
	if(!bSuccess)
	{
		db.Create(lpszFile);

		CString SqlCmd = "CREATE TABLE DemoTable(Name VARCHAR(20),Age VARCHAR(3));";
		db.Execute(SqlCmd);
	
		//打开已创建的数据表
		RecSet.Open(AFX_DAO_USE_DEFAULT_TYPE,
			"SELECT * FROM DemoTable", 0);
		//加入第一个记录,用SQL语句
		db.Execute("INSERT INTO DemoTable (Name,Age) VALUES ('徐景周',26)");
		
		//加入第二个记录,用DAO涵数
		RecSet.AddNew();
		RecSet.SetFieldValue("Name","徐志慧");
		RecSet.SetFieldValue("Age","21");
		RecSet.Update();
		
		//加入第三个记录,用DAO涵数
		RecSet.AddNew();
		RecSet.SetFieldValue("Name","郭徽");
		RecSet.SetFieldValue("Age","27");
		RecSet.Update();
		
		//关闭记录集及库
		RecSet.Close();
		db.Close();

		AfxMessageBox("Access文件写入成功!");
	}
	else
		AfxMessageBox("Demo.mdb数据库已经创建!");
	
}

//////////////////////////////////////////////////////////////////////////////
//名称:OnReadAccess
//功能:从Access文件中读取相应数据并显示出来
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
void CRWAccessDlg::OnReadAccess() 
{
	COleVariant var;		// 字段类型
	var.ChangeType(VT_BSTR, NULL);
	CString strName,strAge,strFile; 

	//清空列表框
	m_AccessList.ResetContent();

	//获取主程序所在路径,存在sPath中
	CString sPath;
	GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
	sPath.ReleaseBuffer ();
    int nPos;
	nPos=sPath.ReverseFind ('\\');
	sPath=sPath.Left (nPos);

	strFile = sPath + "\\demo.mdb";
	db.Open(strFile);		// 打开已创建的demo数据库及DamoTable表
	RecSet.Open(AFX_DAO_USE_DEFAULT_TYPE,"SELECT * FROM DemoTable",NULL);

	while(!RecSet.IsEOF())	// 有没有到表结尾
	{
		RecSet.GetFieldValue("Name",var);
		strName = (LPCSTR)var.pbstrVal;
		RecSet.GetFieldValue("Age",var);
		strAge = (LPCSTR)var.pbstrVal;
		m_AccessList.AddString( strName + " --> "+strAge );

		RecSet.MoveNext();
	}

	//关闭记录集及库
	RecSet.Close();
	db.Close();
}

//////////////////////////////////////////////////////////////////////////////
//名称:OnAbout
//功能:弹出"关于"对话框
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
void CRWAccessDlg::OnAbout() 
{
	CAboutDlg AboutDlg;

	AboutDlg.DoModal();	
}

//////////////////////////////////////////////////////////////////////////////
//名称:OnOK
//功能:退出程序时处理
//作者:徐景周(jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.26
/////////////////////////////////////////////////////////////////////////////
void CRWAccessDlg::OnOK() 
{
	CWindowAnima wa(this);
	
	//将窗体分为6块动画窗体效果
	wa.Scatter6(90,10);
	
	CDialog::OnOK();
}